package com.lepu.app.fun.hospital;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.app.application.MyApplication;
import com.app.utils.Setting;
import com.app.utils.UmengEvent;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.core.ApiClient;
import com.core.lib.core.AsyncRequest;
import com.core.lib.utils.EmojiFilter;
import com.core.lib.utils.main.UIHelper;
import com.core.lib.utils.main.UmengHelper;
import com.core.lib.utils.main.UtilityBase;
import com.eyzhs.app.R;
import com.lepu.app.fun.hospital.adapter.ConsultAdapter;
import com.lepu.app.fun.hospital.bean.Consult;
import com.lepu.app.fun.my.bean.BeanQuestionAnswer;
import com.lepu.app.usercenter.bean.LoginInfo;
import com.lepu.app.widget.CustomTopBarNew;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewLeftLayoutListener;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewRightButtonListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class HospitalConsultMainActivity extends BaseFragmentActivity implements
		OnTopbarNewLeftLayoutListener, OnTopbarNewRightButtonListener,
		AsyncRequest,OnEditorActionListener{

	private static final String REQUEST_DATA = "request_data";
	private static final int MSG_DATA_SUCCESS = 10;
	private static final int MSG_DATA_FAIL = 11;
	private ListView mConsultListView;
	private EditText mConsultEditText;
	private Button mConsultButton;
	private ConsultAdapter mConsultAdapter;
	private ArrayList<Consult> mConsultList;

	private String mReceiveMessage = "";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.hospital_consult_main_activity);
		init();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	/**
	 * 添加页面动画，需要重写这个方法，
	 */
	@Override
	public void onBackPressed() {
		finish(true);
	}

	/**
	 * 初始化方法
	 */
	private void init() {
		// topbar
		CustomTopBarNew topbar = (CustomTopBarNew) findViewById(R.id.topbar);
		topbar.setTopbarTitle("智能在线咨询");
		//topbar.setRightText("常见问题");
		topbar.setonTopbarNewLeftLayoutListener(this);
		//topbar.setOnTopbarNewRightButtonListener(this);

		mConsultListView = (ListView) findViewById(R.id.consult_listview);
		mConsultEditText = (EditText) findViewById(R.id.consult_editText);
		mConsultEditText.setFilters(new InputFilter[] { new EmojiFilter(),
				new InputFilter.LengthFilter(100) });
		mConsultEditText.setOnEditorActionListener(this);
		mConsultButton = (Button) findViewById(R.id.consult_sendbutton);

		mConsultList = new ArrayList<Consult>();
		mConsultAdapter = new ConsultAdapter(HospitalConsultMainActivity.this,
				mConsultList);
		mConsultListView.setAdapter(mConsultAdapter);
		mConsultButton.setOnClickListener(listener);

		mConsultListView.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				UtilityBase.closeSoftInput(HospitalConsultMainActivity.this);
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
			}
		});
		mConsultListView
				.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
	}

	View.OnClickListener listener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			request();
		}
	};

	public void request() {
		String question = mConsultEditText.getText().toString().trim();
		if (TextUtils.isEmpty(question)) {
			UIHelper.showToast(HospitalConsultMainActivity.this, "请输入问题");
			return;
		}

		String url = Setting.getAllQuestionsUrl();

		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);

			if (MyApplication.getInstance().checkIsLogin()) {
				LoginInfo loginInfo = MyApplication.getInstance().getLoginInfo();
				params.put("UserID", loginInfo.UserID);
				params.put("LoginToken", loginInfo.LoginToken);
			}

			// params.put("CategoryID", "-1");//暂时预留

			params.put("Question", question);
			params.put("PageIndex", 1);
			params.put("PageSize", -1);
		} catch (Exception e) {
		}
		map.put("ht", params);
		showProgressDialog();
		ApiClient.http_post(url, map, null, this, REQUEST_DATA, false);
	}

	@SuppressLint("HandlerLeak")
	public Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MSG_DATA_SUCCESS:
				hideProgressDialog();

				// 添加问题
				Consult consultQuestion = new Consult();
				consultQuestion.type = Consult.TYPE_QUESTION;
				consultQuestion.head = mConsultEditText.getText().toString()
						.trim();
				mConsultList.add(consultQuestion);
				mConsultAdapter.notifyDataSetChanged();

				@SuppressWarnings("unchecked")
				ArrayList<BeanQuestionAnswer> dataList = (ArrayList<BeanQuestionAnswer>) msg.obj;
				if (dataList != null && dataList.size() > 0) {

					Consult consult = new Consult();
					consult.type = Consult.TYPE_ANSWER;
					consult.dataList = dataList;
					// consult.desc =
					// "根据您的输入，以下信息供您参考，可逐条点击了解详情。如解决不了您的问题，欢迎拨打电话咨询医生或月嫂~";
					consult.desc = mReceiveMessage;
					mConsultList.add(consult);
				} else {
					Consult consult = new Consult();
					consult.type = Consult.TYPE_ANSWER;
					// consult.desc = "很抱歉不能解决您这个问题，您可以拨打电话咨询医生或月嫂";
					consult.desc = mReceiveMessage;
					mConsultList.add(consult);
				}

				mConsultAdapter.notifyDataSetChanged();
				mConsultEditText.setText("");

				mConsultListView.setSelection(mConsultListView.getCount() - 2);

				break;
			case MSG_DATA_FAIL:
				hideProgressDialog();
				break;

			default:
				break;
			}
		};
	};

	@Override
	public void RequestComplete(Object object, Object data) {

		try {
			JSONObject jsonObject = new JSONObject((String) data);
			JSONObject obj1 = (JSONObject) jsonObject.get("Result");
			JSONObject obj2 = (JSONObject) obj1.get("DetailInfo");

			mReceiveMessage = obj2.optString("Message");
		} catch (JSONException e) {
			e.printStackTrace();
		}

		// 解析json data
		ArrayList<BeanQuestionAnswer> dataArraylist = BeanQuestionAnswer
				.parseJsonData((String) data);

		Message msg = mHandler.obtainMessage();
		msg.what = MSG_DATA_SUCCESS;
		msg.obj = dataArraylist;
		mHandler.sendMessage(msg);
	}

	@Override
	public void RequestError(Object object, int errorId, String errorMessage) {
		mHandler.sendEmptyMessage(MSG_DATA_FAIL);
	}

	@Override
	public void onTopbarLeftLayoutSelected() {
		finish(true);
	}

	@Override
	public void onTopbarRightButtonSelected() {
		
		Intent intent = new Intent(this, HospitalConsultActivity.class);
		startActivity(intent, true);
	}

	@Override
	public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
		switch (actionId) {
		case EditorInfo.IME_ACTION_SEND:
			
			request();
			break;
		}
		return false;
	}
}
